package me.firstapp.weixin.controller.product;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import me.firstapp.common.exception.ServiceException;
import me.firstapp.common.exception.StatusHouse;
import me.firstapp.common.json.ListObject;
import me.firstapp.common.json.SingleObject;
import me.firstapp.common.utils.ResponseUtils;
import me.firstapp.common.utils.StrUtils;
import me.firstapp.module.weixin.activity.RedPackRecord;
import me.firstapp.module.weixin.jinbi.JinBiAccount;
import me.firstapp.module.weixin.member.Member;
import me.firstapp.module.weixin.order.ProductOrder;
import me.firstapp.module.weixin.product.Product;
import me.firstapp.module.weixin.product.ProductCategory;
import me.firstapp.module.weixin.product.ProductSku;
import me.firstapp.service.weixin.account.JinBiAccountService;
import me.firstapp.service.weixin.activity.RedPackRecordService;
import me.firstapp.service.weixin.member.MemberService;
import me.firstapp.service.weixin.product.ProductCategoryService;
import me.firstapp.service.weixin.product.ProductOrderService;
import me.firstapp.service.weixin.product.ProductService;
import me.firstapp.service.weixin.product.ProductSkuService;
import me.firstapp.weixin.controller.base.BaseController;

@Controller
public class ProductController extends BaseController {

	@Autowired
	private ProductCategoryService productCategoryService;

	@Autowired
	private ProductService productService;

	@Autowired
	private MemberService memberService;

	@Autowired
	private ProductOrderService productOrderService;

	@Autowired
	private JinBiAccountService jinBiAccountService;

	@Autowired
	private ProductSkuService productSkuService;

	@Autowired
	private RedPackRecordService redPackRecordService;

	@RequestMapping("/page/productList.htm")
	public ModelAndView productListView(String tag, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		getCurrentLoginOpenId(request, response);
		ProductCategory productCategory = productCategoryService.findByTag(tag);
		if (null == productCategory) {
			throw new ServiceException("error", "分类不存在");
		}
		modelMap.put("productCategory", productCategory);
		return new ModelAndView("product/productList", modelMap);
	}

	@RequestMapping("/page/getProductListData.do")
	public void getProductListData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, Long productCategoryId, HttpServletRequest request,
			HttpServletResponse response) {
		ListObject<JsonProduct> result = new ListObject<>();
		try {
			if (null == productCategoryId) {
				throw new ServiceException(StatusHouse.COMMON_PARAMETER_ERROR);
			}
			String openId = getCurrentLoginOpenId(request, response);
			Member member = memberService.findMemberByOpenId(openId);
			if (null == member) {
				throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
			}
			List<Product> products = productService.findByCategoryId(pageIndex, pageSize, productCategoryId);
			List<JsonProduct> jsonProducts = new ArrayList<>();
			for (Product product : products) {
				JsonProduct jsonProduct = new JsonProduct(product);
				if (Member.VIP_LEVEL_FANS == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("会员");
					jsonProduct.setOtherPrice1(product.getBaseVipPrice());
					jsonProduct.setOtherPriceName2("代理");
					jsonProduct.setOtherPrice2(product.getHighVipPrice());
					jsonProduct.setPrice(product.getFansPrice());
				} else if (Member.VIP_LEVEL_BASE == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("粉丝");
					jsonProduct.setOtherPrice1(product.getFansPrice());
					jsonProduct.setOtherPriceName2("代理");
					jsonProduct.setOtherPrice2(product.getHighVipPrice());
					jsonProduct.setPrice(product.getBaseVipPrice());
				} else if (Member.VIP_LEVEL_HIGHT == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("粉丝");
					jsonProduct.setOtherPrice1(product.getFansPrice());
					jsonProduct.setOtherPriceName2("会员");
					jsonProduct.setOtherPrice2(product.getBaseVipPrice());
					jsonProduct.setPrice(product.getHighVipPrice());
				}
				jsonProducts.add(jsonProduct);
			}
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(jsonProducts);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/searchList.htm")
	public ModelAndView searchListView(String keyword, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		getCurrentLoginOpenId(request, response);
		if (StrUtils.isNULL(keyword)) {
			keyword = "护手霜";
		}
		modelMap.put("keyword", keyword);
		return new ModelAndView("product/searchList", modelMap);
	}

	@RequestMapping("/page/getSearchListData.do")
	public void getSearchListData(@RequestParam(defaultValue = "1") int pageIndex,
			@RequestParam(defaultValue = "20") int pageSize, String keyword, HttpServletRequest request,
			HttpServletResponse response) {
		ListObject<JsonProduct> result = new ListObject<>();
		try {
			String openId = getCurrentLoginOpenId(request, response);
			Member member = memberService.findMemberByOpenId(openId);
			if (null == member) {
				throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
			}
			List<Product> products = productService.findByKeyword(pageIndex, pageSize, keyword);
			List<JsonProduct> jsonProducts = new ArrayList<>();
			for (Product product : products) {
				JsonProduct jsonProduct = new JsonProduct(product);
				if (Member.VIP_LEVEL_FANS == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("会员");
					jsonProduct.setOtherPrice1(product.getBaseVipPrice());
					jsonProduct.setOtherPriceName2("代理");
					jsonProduct.setOtherPrice2(product.getHighVipPrice());
					jsonProduct.setPrice(product.getFansPrice());
				} else if (Member.VIP_LEVEL_BASE == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("粉丝");
					jsonProduct.setOtherPrice1(product.getFansPrice());
					jsonProduct.setOtherPriceName2("代理");
					jsonProduct.setOtherPrice2(product.getHighVipPrice());
					jsonProduct.setPrice(product.getBaseVipPrice());
				} else if (Member.VIP_LEVEL_HIGHT == member.getVipLevel()) {
					jsonProduct.setOtherPriceName1("粉丝");
					jsonProduct.setOtherPrice1(product.getFansPrice());
					jsonProduct.setOtherPriceName2("会员");
					jsonProduct.setOtherPrice2(product.getBaseVipPrice());
					jsonProduct.setPrice(product.getHighVipPrice());
				}
				jsonProducts.add(jsonProduct);
			}
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
			result.setItems(jsonProducts);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/inputOrderInfo.htm")
	public ModelAndView inputOrderInfoView(Long productId, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		Product product = productService.findById(productId);
		if (null == product) {
			throw new ServiceException(StatusHouse.STATUS_PRODUCT_NOT_EXIST);
		}
		modelMap.put("product", product);
		if (Member.VIP_LEVEL_FANS == member.getVipLevel()) {
			modelMap.put("price", product.getFansPrice());
		} else if (Member.VIP_LEVEL_BASE == member.getVipLevel()) {
			modelMap.put("price", product.getBaseVipPrice());
		} else if (Member.VIP_LEVEL_HIGHT == member.getVipLevel()) {
			modelMap.put("price", product.getHighVipPrice());
		}
		modelMap.put("receiveName", member.getReceiveName());
		modelMap.put("receiveAddress", member.getReceiveAddress());
		modelMap.put("receiveMobile", member.getReceiveMobile());

		JSONArray skusArray = new JSONArray();
		List<ProductSku> productSkus = productSkuService.findByProductId(productId);
		for (ProductSku productSku : productSkus) {
			skusArray.add(JSONObject.toJSON(productSku));
		}
		modelMap.put("productSkus", skusArray.toJSONString());
		ProductSku productSku = productSkuService.findByProductIdAndDefault(productId);
		modelMap.put("defaultSku", productSku.getSkuName());
		return new ModelAndView("product/editeProductOrder", modelMap);
	}

	@RequestMapping("/page/confirmProductOrder.do")
	public void confirmProductOrder(Long productId, Integer counts, String receiveName, String receiveMobile,
			String receiveAddress, String remark, String skuName, HttpServletRequest request,
			HttpServletResponse response) {
		SingleObject<ProductOrder> result = new SingleObject<>();
		try {
			if (null == productId || null == counts || StrUtils.isNULL(receiveName) || StrUtils.isNULL(receiveMobile)
					|| StrUtils.isNULL(receiveAddress)) {
				throw new ServiceException("error", "必填项不能为空");
			}
			if (counts == 0) {
				throw new ServiceException("error", "购买数量不能为0");
			}
			if (!StrUtils.isMobile(receiveMobile)) {
				throw new ServiceException("error", "手机号码格式有误");
			}
			String openId = getCurrentLoginOpenId(request, response);
			if (1603 == productId) {
				RedPackRecord redPackRecord = redPackRecordService.findByProductIdAndOpenId(productId, openId);
				if (null != redPackRecord) {
					throw new ServiceException("error", "你已经兑换过，只可兑换一次！");
				}
			}
			ProductOrder productOrder = productOrderService.executeCreateOrder(openId, productId, counts, receiveName,
					receiveMobile, receiveAddress, remark, skuName);
			try {
				Member member = memberService.findMemberByOpenId(openId);
				member.setReceiveName(receiveName);
				member.setReceiveAddress(receiveAddress);
				member.setReceiveMobile(receiveMobile);
				memberService.executeUpdateMember(member);
			} catch (Exception e) {
				e.printStackTrace();
			}
			result.setObject(productOrder);
			result.setStatusObject(StatusHouse.COMMON_STATUS_OK);
		} catch (ServiceException e) {
			e.printStackTrace();
			result.setStatusObject(e.getStatusObject());
		} catch (Exception e) {
			e.printStackTrace();
			result.setStatusObject(StatusHouse.COMMON_STATUS_ERROR);
		}
		ResponseUtils.renderJson(response, result);
	}

	@RequestMapping("/page/confirmProductOrderView.htm")
	public ModelAndView confirmProductOrderView(String orderNo, HttpServletRequest request,
			HttpServletResponse response, ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		Member member = memberService.findMemberByOpenId(openId);
		if (null == member) {
			throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
		}
		JinBiAccount jinBiAccount = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(member.getCardNo(), openId);
		ProductOrder productOrder = productOrderService.findByOrderNo(openId, orderNo);
		Product product = productService.findById(productOrder.getProductId());
		productOrder.setUnit(product.getUnit());
		modelMap.put("jbalance", jinBiAccount.getBalance());
		modelMap.put("order", productOrder);
		return new ModelAndView("product/confirmProductOrder", modelMap);
	}

	@RequestMapping("/page/productOrderDetailView.htm")
	public ModelAndView productOrderDetailView(String orderNo, HttpServletRequest request, HttpServletResponse response,
			ModelMap modelMap) {
		String openId = getCurrentLoginOpenId(request, response);
		ProductOrder productOrder = productOrderService.findByOrderNo(openId, orderNo);
		Product product = productService.findById(productOrder.getProductId());
		productOrder.setUnit(product.getUnit());
		modelMap.put("order", productOrder);

		if (ProductOrder.STATUS_NOT_PAY == productOrder.getStatus()) {
			Member member = memberService.findMemberByOpenId(openId);
			if (null == member) {
				throw new ServiceException(StatusHouse.STATUS_PAGE_ERROR_NOT_CONCERN_WEIXIN);
			}
			JinBiAccount jinBiAccount = jinBiAccountService.findJinBiAccountByCardNoAndOpenId(member.getCardNo(),
					openId);
			modelMap.put("jbalance", jinBiAccount.getBalance());
		}
		return new ModelAndView("product/productOrderDetail", modelMap);
	}
}
